﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;

namespace XYZCompiler
{
    internal class XYZType
    {
        public XYZType(XYZType parent,string name)
        {
            this.parent = parent;
            Name = name;
        }

        public int row = 0;
        public int column = 0;
        public string Name { get; private set; }
        public XYZType GetField(string name)
        {
            if (_varTable.ContainsKey(name))
                return _varTable[name];
            if (parent != null)
                return parent.GetField(name);
             return NULLType;
        }

        public bool IsType(XYZType type)
        {
            if (Name == "literal" && (type.Name == "int" || type.Name == "long"))
                return true;
            if (type == this)
                return true;
            if (parent != null)
                return parent.IsType(type);
            return false;

        }
        public  IEnumerable<XYZMethod> GetMethod(string name,int count)
        {
            var m = (from method in _methodTable
                     where method.Name == name && method._paramsList.Count == count
                     select method);
            return m;
        }
        public XYZMethod PickMethod(string name,List<XYZType> ps )
        {
            var candicates = GetMethod(name, ps.Count());
            if (candicates == null)
                return null;
            foreach (var xyzMethod in candicates)
            {
                bool fit = true;
                for(int i =0;i<xyzMethod._paramsList.Count;i++)
                {
                    if (!ps[i].IsType(xyzMethod._paramsList[i]))
                    {
                        fit = false;
                        break;
                    }

                }
                if (fit)
                    return xyzMethod;
            }
            return null;

        }
        public static readonly XYZType NULLType = new XYZType(null,"NULL");
        public XYZType parent = null;
        public Dictionary<string, XYZType> _varTable = new Dictionary<string, XYZType>();
        public List<XYZMethod> _methodTable = new List<XYZMethod>();
    }
}
